/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBean.TX.SABM;

import entity.*;
import exception.ExistException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperRunManager;
import session.TX.OutletSBRemote;

//Imports for primefaces maps
import org.primefaces.event.map.MarkerDragEvent;    
import org.primefaces.model.map.Marker; 

/**
 *
 * @author TWD
 */
@ManagedBean(name = "outletManagerBean")
@ViewScoped
public class OutletMB {
    @Resource(name = "foodsage")
    private DataSource foodsage;

    @EJB
    private OutletSBRemote outlet;
    
 
    private String outletName;
    private String outletAddress;
    private String phoneNumber;
    private Stakeholder stakeholder;
    private String statusMessage;
    private Outlet selectedOutlet;
    private Integer month1;
    private Integer year;

    long outletId;
    
    private double latitude = 0, longitude = 0;
    
    
    //Data fields for creating outlet manager
    private String outletManager_email;
    private Long outletID;
    
    
    public OutletMB() {
    }
    
public void generateReport (ActionEvent event) {
     outletId = (Long)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("outletId");
        try
        {   
            int month = getMonth1() -1;
            Calendar lowerBound = Calendar.getInstance();
            lowerBound.set(getYear(), month, 1);
           
            Calendar upperBound = Calendar.getInstance();
            int lastDayOfMonth = lowerBound.getActualMaximum(Calendar.DAY_OF_MONTH);  
            upperBound.set(getYear(), month, lastDayOfMonth);

            ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
            
            String lowerBound_string = "'" + getYear() + "-" + getMonth1() + "-" + lowerBound.get(Calendar.DATE) + " 00:00:00.0'";
            String upperBound_string = "'" + getYear() + "-" + getMonth1() + "-" + upperBound.get(Calendar.DATE) + " 00:00:00.0'";
            
           String strSQL = "SELECT TIME_STAMP AS PURCHASEDITEM_TIME_STAMP, QUANTITY AS PURCHASEDITEM_QUANTITY, ITEM_NAME AS PURCHASEDITEM_ITEM_NAME, SUBTOTAL AS PURCHASEDITEM_SUBTOTAL FROM PURCHASEDITEM"
                   +  " WHERE TIME_STAMP BETWEEN " + lowerBound_string + " AND " + upperBound_string + " AND OUTLET_ID = " + outletId;
                                           
            ResultSet rsAddresses = foodsage.getConnection().prepareStatement(strSQL).executeQuery();
            JRResultSetDataSource jrResultSetDataSource = new JRResultSetDataSource(rsAddresses);
            InputStream reportStream = ((HttpSession)ec.getSession(true)).getServletContext().getResourceAsStream("/jasperreports/outletReport.jasper");
            
            ec.setResponseContentType("application/pdf");
            OutputStream outputStream = ec.getResponseOutputStream(); 
            
            JasperRunManager.runReportToPdfStream(reportStream, outputStream, new HashMap(), jrResultSetDataSource);
            
            outputStream.flush();
            outputStream.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
    
     public void generateReservationReport (ActionEvent event) {
         outletId = (Long)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("outletId");
        try
        {   
            int month = getMonth1() -1;
            Calendar lowerBound = Calendar.getInstance();
            lowerBound.set(getYear(), month, 1);
           
            Calendar upperBound = Calendar.getInstance();
            int lastDayOfMonth = lowerBound.getActualMaximum(Calendar.DAY_OF_MONTH);  
            upperBound.set(getYear(), month, lastDayOfMonth);

            ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
            
            String lowerBound_string = "'" + getYear() + "-" + getMonth1() + "-" + lowerBound.get(Calendar.DATE) + " 00:00:00.0'";
            String upperBound_string = "'" + getYear() + "-" + getMonth1() + "-" + upperBound.get(Calendar.DATE) + " 00:00:00.0'";
            
           String strSQL = "SELECT AREA_ID AS OUTLETRESERVATION_AREA_ID, CUSTOMERSHOWUP AS OUTLETRESERVATION_CUSTOMERSHOWUP, NUMPPL AS OUTLETRESERVATION_NUMPPL, TSTIME AS OUTLETRESERVATION_TSTIME, TIMESLOT AS OUTLETRESERVATION_TIMESLOT FROM OUTLETRESERVATION"
                   +  " WHERE TIMESLOT BETWEEN " + lowerBound_string + " AND " + upperBound_string + " AND CONFIRMSTATUS = TRUE AND OUTLET_ID = " + outletId;
                                           
            ResultSet rsAddresses = foodsage.getConnection().prepareStatement(strSQL).executeQuery();
            JRResultSetDataSource jrResultSetDataSource = new JRResultSetDataSource(rsAddresses);
            InputStream reportStream = ((HttpSession)ec.getSession(true)).getServletContext().getResourceAsStream("/jasperreports/reservationReport.jasper");
            
            ec.setResponseContentType("application/pdf");
            OutputStream outputStream = ec.getResponseOutputStream(); 
            
            JasperRunManager.runReportToPdfStream(reportStream, outputStream, new HashMap(), jrResultSetDataSource);
            
            outputStream.flush();
            outputStream.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }


    public void createOutlet(ActionEvent event) {
        
        //Check the lat and long
        if(longitude < 103.593407 || longitude > 104.045219 || latitude < 1.235865 || latitude > 1.473035){
            System.out.println("Outside boundary!");
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Please ensure the location marker is inside Singapore!", "")); 
            return;
        }  
        
        //Creating outlet
        String outletname = String.valueOf(getOutletName());
        String phonenumber = String.valueOf(getPhoneNumber());
        String outletaddress = String.valueOf(getOutletAddress());
        
        //pull the stakeholder name from the session
        Long stakeholderID = (Long)FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholderId");
        try {
            getOutlet().createOutlet(stakeholderID, outletname, phonenumber, outletaddress, latitude, longitude);
            setStatusMessage(outletName + " created successfully");
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Result: " + getStatusMessage(), ""));      
           

        } 
        catch (ExistException eex) {
            setStatusMessage("Error");
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Result: " + getStatusMessage(), ""));
        } 
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public List<Outlet> getAllOutlets() {
        return getOutlet().getAllOutlets();
    }

    public List<Outlet> getOutletsByStakeholder() {
        String stakeholderName = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholderName").toString();
        return outlet.getOutletByStakeholder(stakeholderName);
    }
    
    public List<Outlet> getSpecificOutlet(ActionEvent event) {
        String o = String.valueOf(outletName);
        return getOutlet().getSpecificOutlet(o);
    }

    public void deleteOutlet(Outlet o) {
        Long outletId = o.getId();
        String outletName = o.getOutletName();
        setStatusMessage(outletName + " deleted successfully");
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Result: " + getStatusMessage(), ""));
        outlet.deleteOutlet(outletId);
    }

    public void updateFields() {
        System.out.println("UpdateFields");
        this.outletName = selectedOutlet.getOutletName();
        this.phoneNumber = selectedOutlet.getPhoneNumber();
    }
    
    


    
    public List<String> getOutletManagerEmailsbyOutlet(){
        
        if (selectedOutlet == null) return new ArrayList<String>();
        outletID = selectedOutlet.getId();
        return outlet.getOutletManagerEmailsbyOutlet(outletID);
    }
    
    
    
    public void createOutletManager(){
        outletID = selectedOutlet.getId();
        System.out.println("OutletMB: Adding " + outletManager_email  +" as a manager of outlet "+ outletID);
        String statusMSG = outlet.addManagerToOutlet(outletManager_email, outletID);   
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMSG, "")); 
        outletManager_email = "";
    }
    
    public void deleteOutletManager(){
        
        if(outletManager_email == null){
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "No manager to delete!", ""));
            return;
        }
        
        outletID = selectedOutlet.getId();
        System.out.println("OutletMB: Removing " + outletManager_email  +" as a manager of outlet "+ outletID);
        String statusMSG = outlet.removeManagerFromOutlet(outletManager_email, outletID);
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMSG, "")); 
        outletManager_email = "";
    }
    
    
    public void getLatLong(MarkerDragEvent event) {  
        Marker marker = (Marker) event.getMarker(); 
        
        latitude = marker.getLatlng().getLat();
        longitude = marker.getLatlng().getLng();
        
    }  
    
    
    
    
    

    public String getOutletName() {
        return outletName;
    }

    public void setOutletName(String outletName) {
        this.outletName = outletName;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public Stakeholder getStakeholder() {
        return stakeholder;
    }

    public void setStakeholder(Stakeholder stakeholder) {
        this.stakeholder = stakeholder;
    }

    /**
     * @return the outlet
     */
    public OutletSBRemote getOutlet() {
        return outlet;
    }

    /**
     * @param outlet the outlet to set
     */
    public void setOutlet(OutletSBRemote outlet) {
        this.outlet = outlet;
    }

    /**
     * @return the statusMessage
     */
    public String getStatusMessage() {
        return statusMessage;
    }

    /**
     * @param statusMessage the statusMessage to set
     */
    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    /**
     * @return the selectedOutlet
     */
    public Outlet getSelectedOutlet() {
        return selectedOutlet;
    }

    /**
     * @param selectedOutlet the selectedOutlet to set
     */
    public void setSelectedOutlet(Outlet selectedOutlet) {
        this.selectedOutlet = selectedOutlet;
    }

    /**
     * @return the outletAddress
     */
    public String getOutletAddress() {
        return outletAddress;
    }

    /**
     * @param outletAddress the outletAddress to set
     */
    public void setOutletAddress(String outletAddress) {
        this.outletAddress = outletAddress;
    }

    /**
     * @return the outletManager_email
     */
    public String getOutletManager_email() {
        return outletManager_email;
    }

    /**
     * @param outletManager_email the outletManager_email to set
     */
    public void setOutletManager_email(String outletManager_email) {
        this.outletManager_email = outletManager_email;
    }

    /**
     * @return the outletID
     */
    public Long getOutletID() {
        return outletID;
    }

    /**
     * @param outletID the outletID to set
     */
    public void setOutletID(Long outletID) {
        this.outletID = outletID;
    }

    /**
     * @return the latitude
     */
    public double getLatitude() {
        return latitude;
    }

    /**
     * @param latitude the latitude to set
     */
    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }

    /**
     * @return the longitude
     */
    public double getLongitude() {
        return longitude;
    }

    /**
     * @param longitude the longitude to set
     */
    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }

    /**
     * @return the month1
     */
    public Integer getMonth1() {
        return month1;
    }

    /**
     * @param month1 the month1 to set
     */
    public void setMonth1(Integer month1) {
        this.month1 = month1;
    }

    /**
     * @return the year
     */
    public Integer getYear() {
        return year;
    }

    /**
     * @param year the year to set
     */
    public void setYear(Integer year) {
        this.year = year;
    }

    
    

    
}
